import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import { showFailToast } from 'vant'
import { useUserStore } from '@/stores/user'
import { useGlobalStore } from '@/stores/global'

// 禁用进度环
NProgress.configure({ showSpinner: false })

// 全局前置守卫 访问某个路由之前守卫
// - to: 将要访问哪个路由
// - from: 从那个路由来
// - next: 路由放行函数
router.beforeEach((to, from, next) => {

  NProgress.start()
  // 登录拦截判断
  const userStore = useUserStore()
  const useGlobal = useGlobalStore()

  // keepAlive 滚动逻辑处理
  if (from.matched.some(m => m.meta.scrollState)) {
    useGlobal.scrollKeyValue.set(from.path, document.documentElement.scrollTop)
  }
  // 登陆拦截操作
  if (to.matched.some(m => m.meta.auth)) {
    if (userStore.isLogin) {
      next();
    } else {
      showFailToast('请登录后操作！')
      next('/login')
    }
  } else {
    next();
  }
  
  document.title = 'ViteMobileApp ' + to.meta.title
})

// 全局后置守卫
router.afterEach((to, from) => {
  
  NProgress.done()
  // 登录拦截判断
  const useGlobal = useGlobalStore()

  if (to.meta.scrollState == true) {
    let scrollTop = useGlobal.scrollKeyValue.get(to.path)
    nextTick().then(() => {
      document.documentElement.scrollTop = scrollTop
    })
  } else {
    nextTick().then(() => {
      document.documentElement.scrollTop = 0
    })
  }
})
